package com.maiyuren.fishkit.utils

import androidx.annotation.RawRes
import com.maiyuren.fishkit.FishkitApplication
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

object FishResourceFileUtils {
    fun readAllBytes(@RawRes id: Int): ByteArray? {
        val tempStream: InputStream = FishkitApplication.instance.resources.openRawResource(id)
        if (tempStream == null) return null

        val tempBuffer = ByteArray(64 * 1024) // 64K per time

        val bufList = mutableListOf<ByteArray>()
        var totalLen = 0;
        while (tempStream.available() > 0) {
            val readLen = tempStream.read(tempBuffer)
            if (readLen > 0) {
                bufList.add(tempBuffer.copyOfRange(0, readLen))
                totalLen += readLen
            }
            if (readLen < 64 * 1024) {
                break
            }
        }

        tempStream.close()

        val ret = ByteArray(totalLen)
        var offset = 0
        bufList.forEach {
            it.copyInto(ret, offset)
            offset += it.size
        }
        return ret;
    }

    fun open(@RawRes id: Int, copy: Boolean = true): InputStream? {
        if (!copy) {
            return FishkitApplication.instance.resources.openRawResource(id)
        }

        // 先拿当前版本
        val cfgKey = "${FishStorage.keys.resource_file_pre}${id}"
        val lastVer = FishStorage.getString(cfgKey)
        val currAppVersion = FishAppUtils.getVersion()
        if (null == currAppVersion) return null
        val sdFilePath = FishkitApplication.instance.filesDir.absolutePath + "/resource/" + id.toString()
        val sdFile = File(sdFilePath)

        // 如果有APP更新，则直接替换，并更新配置为当前版本，避免重复复制
        if (currAppVersion != lastVer || !sdFile.exists()) {
            val folderPathPos = sdFilePath.lastIndexOf('/')
            val folderPath  = sdFilePath.substring(0, folderPathPos)
            File(folderPath).mkdirs()
            val tempStream: InputStream = FishkitApplication.instance.resources.openRawResource(id)
            val outStream = FileOutputStream(sdFile, false)
            val tempBuffer = ByteArray(64 * 1024) // 64K per time

            while (tempStream.available() > 0) {
                val readLen = tempStream.read(tempBuffer)
                if (readLen > 0) {
                    outStream.write(tempBuffer, 0, readLen)
                }
                if (readLen < 64 * 1024) {
                    break
                }
            }

            outStream.close()

            tempStream.close()
            FishStorage.setString(cfgKey, currAppVersion)
        }

        return sdFile.inputStream();
    }
}